package test.enba.openfeign.controller;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import lombok.Data;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** 自定义错误响应控制器 */
@RestController
public class CustomErrorController implements ErrorController {

  @RequestMapping("/system-error")
  public ResponseEntity<?> handleError(HttpServletRequest request) {

    Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

    if (status != null) {
      Integer statusCode = Integer.valueOf(status.toString());

      // 获取异常对象
      Exception exception = (Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);

      // 自定义响应体
      CustomErrorResponse errorResponse = new CustomErrorResponse();
      errorResponse.setStatus(statusCode);
      errorResponse.setMessage(HttpStatus.valueOf(statusCode).getReasonPhrase());
      if (exception != null) {
        errorResponse.setDetail(exception.getMessage());
      }

      return new ResponseEntity<>(errorResponse, HttpStatus.valueOf(statusCode));
    } else {
      return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("未知错误");
    }
  }

  // 自定义的错误响应实体
  @Data
  private static class CustomErrorResponse {
    private int status;
    private String message;
    private String detail;
  }
}
